package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.data.redis.domain.geo.GeoShape;
import org.springframework.data.redis.domain.geo.Metrics;
import org.springframework.stereotype.Service;
import cn.hutool.json.JSONUtil;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;
import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    /**
     * 根据id查询商铺信息
     * @param id 商铺id
     * @return 商铺详情数据
     */
    @Override
    public Result queryById(Long id) {
        //缓存空对象解决缓存穿透问题
        // shop = processWithNullKey(id);
        Shop shop=cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,
                  id,Shop.class,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES,this::getById);

        //采用互斥锁解决缓存击穿问题
        //Shop shop = processWithLock(id);

        //逻辑缓存解决缓存击穿问题
        //Shop shop = processWithLogicTimeOut(id);
//        Shop shop=cacheClient.queryWithLogicTimeOut(RedisConstants.CACHE_SHOP_KEY,
//                  id,Shop.class,20L,TimeUnit.SECONDS,this::getById);

        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }
    /**
     * 更新商铺信息
     * @param shop 商铺数据
     * @return 无
     */
    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        // 1.判断id是否存在，不存在则返回错误信息
        Long id = shop.getId();
        if(id==null){
            return Result.fail("店铺id不能为空！");
        }
        // 2.更新数据库
        updateById(shop);
        // 3.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+id);
        return Result.ok();
    }

    @Override
    public Result queryShopType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否存在x，y坐标
        if (x==null || y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page);
        }
        // 2.计算页面的start和end
        int from=(current-1)*DEFAULT_PAGE_SIZE;
        int end=current*DEFAULT_PAGE_SIZE;
        // 3.根据需要页面数据进行坐标的计算并返回distance数据
        String key=SHOP_GEO_KEY+typeId;

        /*GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key
                , GeoReference.fromCoordinate(x, y)
                , new Distance(5000)
                , RedisGeoCommands.GeoRadiusCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );*/

        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().radius(
                key,
                new Circle(
                        new Point(x, y),  // 中心点坐标 (x, y)
                        new Distance(5000, Metrics.METERS) // 半径 5000 米
                ),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                        .includeDistance()                 // 返回距离
                        .limit(end)
        );
        if(results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(from>=list.size()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids=new ArrayList<>(list.size());
        Map<String,Double> map=new HashMap<>(list.size());
        list.stream().skip(from).forEach(geoResult -> {
            String strId = geoResult.getContent().getName();
            ids.add(Long.parseLong(strId));
            double distance = geoResult.getDistance().getValue();
            map.put(strId, distance);
        });
        // 4.根据shopId查询shop
        String join = StrUtil.join(",",ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id," + join + ")").list();
        for (Shop shop:shops) {
            shop.setDistance(map.get(shop.getId().toString()));
        }
        // 5.返回数据
        return Result.ok(shops);
    }


     /*
    public Shop processWithNullKey(Long id) {
        // 1.查询商品id是否存在于redis中
        String key= RedisConstants.CACHE_SHOP_KEY+id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2.如果存在则直接返回
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, Shop.class);
        }
        // json为“”或者null，如果不为null那么就是空，空的话就直接返回错误信息，null的话就查询数据库
        if (json!=null){
            return null;
        }
        // 3.如果不存在则查询数据库
        Shop shop = getById(id);
        // 4.数据库中如果不存在该id，则返回错误
        if(shop==null){
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        // 5.存在，则先将数据存入redis中
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }*/

    /**
     * 互斥锁
     * @param id
     * @return
     */
    public Shop processWithLock(Long id) {
        // 1.查询商品id是否存在于redis中
        String key= RedisConstants.CACHE_SHOP_KEY+id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2.如果存在则直接返回
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, Shop.class);
        }
        // json为“”或者null，如果不为null那么就是空，空的话就直接返回错误信息，null的话就查询数据库
        if (json!=null){
            return null;
        }
        // 3.如果不存在则查询数据库
        // 3.1尝试获取互斥锁
        Boolean isLock = tryLock(RedisConstants.LOCK_SHOP_KEY+id);
        // 3.2判断是否能获取锁，不能则进行休眠
        Shop shop = null;
        try {
            if(!isLock){
                Thread.sleep(100);
                return processWithLock(id);
            }
            // 3.3如果获得则进入下一步操作：查询数据库
            shop = getById(id);
            // 重建模拟延时
            Thread.sleep(200);
            // 4.数据库中如果不存在该id，则返回错误
            if(shop==null){
                stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            // 5.存在，则先将数据存入redis中
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 8.释放锁
            unLock(RedisConstants.LOCK_SHOP_KEY+id);
        }
        return shop;
    }

    /*private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);

    public Shop processWithLogicTimeOut(Long id) {
        // 1.查询商品id是否存在于redis中
        String strRedisData = stringRedisTemplate.opsForValue().get(RedisConstants.REDIS_SHOP_KEY + id);
        // 2.未命中，返回空
        if(StrUtil.isBlank(strRedisData)){
            return null;
        }
        // 3.命中
        // 3.1 判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(strRedisData, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 3.2 未过期，返回商铺信息
        if(expireTime.isAfter(LocalDateTime.now())){
            return shop;
        }
        // 3.3 过期，尝试获取互斥锁
        String lockKey= RedisConstants.LOCK_SHOP_KEY+id;
        Boolean isLock = tryLock(lockKey);
        // 4.判断是否取锁
        if(isLock){
            // 4.1 再次判断Redis是否有新缓存
            strRedisData=stringRedisTemplate.opsForValue().get(RedisConstants.REDIS_SHOP_KEY + id);
            redisData=JSONUtil.toBean(strRedisData, RedisData.class);
            expireTime=redisData.getExpireTime();
            if(expireTime.isAfter(LocalDateTime.now())){
                return JSONUtil.toBean((JSONObject) redisData.getData(),Shop.class);
            }
            // 4.2 开启新线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    // 重建缓存
                    this.saveShop(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });

        }
        // 5 返回旧商铺信息
        return shop;
    }*/

    /**
     * 逻辑保存商店信息
     * @param id
     * @param expireTime
     */
    /*public void saveShop(Long id,Long expireTime) throws InterruptedException {
        RedisData redisData = new RedisData();

        // 模拟重建缓存过程
        Thread.sleep(200);

        redisData.setData(getById(id));
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(RedisConstants.REDIS_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }*/
    /**
     * 尝试获取互斥锁
     * @param key
     * @return
     */
    private Boolean tryLock(String key){
        // 1.尝试存入redis中，采用setnx存储查看返回值
        // 这里要注意死锁问题所以应该设置ttl
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "lock",RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        // 处理包装类拆箱问题
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 解锁
     * @param key
     */
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
